<template>
  <div class="course-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑课程' : '创建课程' }}</h2>
      <el-button @click="$router.push('/courses')">返回课程列表</el-button>
    </div>
    
    <el-card class="box-card">
      <el-form ref="courseForm" :model="courseForm" :rules="rules" label-width="100px">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="courseForm.title" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        
        <el-form-item label="课程封面">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload">
            <img v-if="courseForm.cover" :src="courseForm.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">推荐尺寸: 800 x 450</div>
        </el-form-item>
        
        <el-form-item label="课程简介" prop="description">
          <el-input type="textarea" v-model="courseForm.description" :rows="4" placeholder="请输入课程简介"></el-input>
        </el-form-item>
        
        <el-form-item label="课程价格" prop="price">
          <el-input-number v-model="courseForm.price" :precision="2" :step="10" :min="0"></el-input-number>
          <span class="form-tip">设置为0表示免费课程</span>
        </el-form-item>
        
        <el-form-item label="课程状态">
          <el-radio-group v-model="courseForm.status">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="2">下线</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getCourseById, createCourse, updateCourse } from '@/api/course';

export default {
  name: 'CourseEdit',
  data() {
    return {
      isEdit: false,
      courseId: null,
      loading: false,
      courseForm: {
        title: '',
        description: '',
        cover: '',
        teacherId: '',
        price: 0,
        status: 0,
        lessonCount: 0,
        enrollCount: 0
      },
      rules: {
        title: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入课程简介', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['teacherId'])
  },
  created() {
    // 设置教师ID
    this.courseForm.teacherId = this.teacherId;
    
    // 判断是编辑还是创建
    if (this.$route.params.id) {
      this.isEdit = true;
      this.courseId = this.$route.params.id;
      this.fetchCourseDetail();
    }
  },
  methods: {
    fetchCourseDetail() {
      if (!this.courseId) return;
      
      this.loading = true;
      getCourseById(this.courseId)
        .then(response => {
          const { data } = response;
          if (data) {
            this.courseForm = data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleCoverSuccess(res, file) {
      // 实际项目中应该使用后端返回的URL
      this.courseForm.cover = URL.createObjectURL(file.raw);
    },
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传封面图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传封面图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    submitForm() {
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          
          const submitAction = this.isEdit 
            ? updateCourse(this.courseForm) 
            : createCourse(this.courseForm);
          
          submitAction
            .then(() => {
              this.$message({
                type: 'success',
                message: this.isEdit ? '课程更新成功!' : '课程创建成功!'
              });
              this.$router.push('/courses');
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.courseForm.resetFields();
      if (this.isEdit) {
        this.fetchCourseDetail();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.course-edit-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      
      &:hover {
        border-color: #409EFF;
      }
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    
    .avatar {
      width: 178px;
      height: 100px;
      display: block;
    }
  }
  
  .upload-tip, .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
  
  .form-tip {
    margin-left: 10px;
  }
}
</style> 